package cn.yzx.pethome.system.login.controller;

import cn.yzx.pethome.constants.BaseConstants;
import cn.yzx.pethome.system.login.domain.PhoneRegister;
import cn.yzx.pethome.system.user.domain.User;
import cn.yzx.pethome.system.user.service.IUserService;
import cn.yzx.pethome.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/register")
@Api(value = "注册API" , description = "注册的功能")
public class RegisterController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IUserService userService;

    @ApiOperation(value = "手机号注册" )
    @PostMapping("/phone")
    public AjaxResult register(@RequestBody PhoneRegister register){
        //校验填入的手机号(用户名)是否为空
        if(register.getPhone() == null || "".equals(register.getPhone().trim())){
            return AjaxResult.error().setMsg("手机号不能为空，请输入手机号！");
        }
        if(register.getPhoneCode() == null || "".equals(register.getPhoneCode().trim())){
            return AjaxResult.error().setMsg("手机验证码不能为空！");
        }

        //校验输入的两次密码是否为空  且是否相同
        String password = register.getPassword();
        String passwordRepeat = register.getPasswordRepeat();
        if(password == null || "".equals(password.trim())){
            return AjaxResult.error().setMsg("请输入密码！");
        }
        if(passwordRepeat == null || "".equals(passwordRepeat.trim())){
            return AjaxResult.error().setMsg("输入确认密码不能为空！");
        }
        if(!password.equals(passwordRepeat)){
            return AjaxResult.error().setMsg("两次密码不相同，请重新输入！");
        }

        //校验手机号验证码是否正确
        String key = register.getPhone()+ BaseConstants.Vcode.REGISTER;
        Object value = redisTemplate.opsForValue().get(key);
        if(value == null){
            return AjaxResult.error().setMsg("手机验证码已过期！");
        }
        if(!register.getPhoneCode().equals(value.toString())){
            return AjaxResult.error().setMsg("手机验证码输入错误！");
        }

        User byPhone = userService.findByPhone(register.getPhone());
        if(byPhone != null){
            return AjaxResult.error().setMsg("该手机号已被注册");
        }
        userService.add(register);
        return AjaxResult.success().setMsg("注册成功！");
    }

}
